<?php

namespace app\common\exception;

use app\common\respond\HttpApi;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\Response;
use Throwable;

class ExceptionHandle extends Handle
{
    public function render($request,Throwable $e): Response
    {
        // 参数验证错误
        if ($e instanceof  ValidateException) {
            $respond = new HttpApi();
            return $respond->error($e->getError(),-1);
        }

        //业务逻辑异常
        if ($e instanceof LogicException) {
            return json([
                'code' => $e->getCode(),
                'msg' => $e->getMessage()
            ]);
        }

        // 请求异常
        if ($e instanceof HttpException && $request->isAjax()) {
            return response($e->getMessage(), $e->getStatusCode());
        }

        // 其他错误交给系统处理
        return parent::render($request, $e);
    }

}